package com.example.demo.webClient;

import com.example.cato_entity.entity.Ingredient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Configuration
public class WebClient_ {


    @Bean
   public WebClient webClient(){
       return WebClient.create();
   }

    public void getOne(String id){
        Mono<Ingredient> ingredientMono = WebClient.create()
                .get()
                .uri("http://localhost:8080/ingredients/{id}",id)
                .retrieve()               //// 会执行请求
                .onStatus(HttpStatus::is4xxClientError,clientResponse -> Mono.just(new UnknownError()))    //处理错误
                .bodyToMono(Ingredient.class);   // 将响应体的载荷抽取到Mono<Ingredient>

         // 如果想对返回的Mono进行额外的操作，就要在请求发送之前进行订阅
        ingredientMono.subscribe(ingredient -> {},
                error->{});
    }
   /*
      retrieve方法会返回一个ResponseSpec对象，exchange方法会返回一个ClientResponse类型的Mono对象，可以使用响应中的数据，包括载荷，头信息和cookie'
    */
    public void getOne_(String id){
        Mono<Ingredient> ingredientMono = WebClient.create()
                .get()
                .uri("http://localhost:8080/ingredients/{id}",id)
                .exchange()            // 会执行请求
                .flatMap(cr->cr.bodyToMono(Ingredient.class));

        // 如果想对返回的Mono进行额外的操作，就要在请求发送之前进行订阅
        ingredientMono.subscribe(ingredient -> {},
                error->{});
    }

    public void postOne(){
        Mono<Ingredient> ingredientMono = null;

        Mono<Ingredient> result = webClient()
                .post()
                .uri("/ingredient")
                .body(ingredientMono,Ingredient.class)
                .retrieve()
                .bodyToMono(Ingredient.class);

        // 如果没有发送的Flux ，只有原始数据
        Ingredient ingredient = null;
        Mono<Ingredient> result_ = webClient()
        .post()
        .uri("/ingredients")
        .syncBody(ingredient)        //发送原始对象
        .retrieve()
        .bodyToMono(Ingredient.class);
        result.subscribe(i->{});
    }


    public void deleteOne(String id){
        Mono<Void> result  =webClient()
                .delete()
                .uri("/ingredients/{id}",id)
                .retrieve()
                .bodyToMono(Void.class);

        result.subscribe(i->{});

    }
}
